import Kurento from "kurento-client";
import {lConfig} from "../config/config";
import EventEmitter from "events";

const { wsUri } = lConfig.kurentoServer;

export default class Client extends EventEmitter {
  private client: Kurento = null;

  constructor() {
    super();
  }

  getClient(callback) {
    if (this.client !== null) {
      return callback(null, this.client);
    }

    Kurento(wsUri, (error, kurentoClient) => {
      if (error) {
        console.log("Could not find media server at address " + wsUri);
        return callback("Could not find media server at address" + wsUri
          + ". Exiting with error " + error);
      }

      this.client = kurentoClient;
      callback(null, kurentoClient);
    });
  }

  connect(originEndpoint, targetEndpoint) {
    originEndpoint.connect(targetEndpoint, (error) => {
      if (error) {
        return error && error();
      }
    })
  }

  initEndpoint (client, cb) {
    this.createMediaPipeline(client, (pipeline) => {
      this.createEndpoint(pipeline, (endpoint) => {
        // 回调
        if (cb) cb(endpoint, pipeline)
      })
    });
  }

  onIceCandidate (webRtcEndpoint, cb) {
    // IceCandidateFound OnIceCandidate
    webRtcEndpoint.on('IceCandidateFound', (event) => {
      var iceCandidate = Kurento.getComplexType('IceCandidate')(event.candidate);
      cb(iceCandidate);
    });
  }

  createMediaPipeline (client, cb) {
    client.create('MediaPipeline', (error, pipeline) => {
      if (error) {
        return error && error(error);
      }
      cb && cb(pipeline)
    })
  }

  createEndpoint (pipeline, cb) {
    pipeline.create('WebRtcEndpoint', (error, webRtcEndpoint) => {
      if (error) {
        return error && error(error);
      }
      cb && cb(webRtcEndpoint)
    })
  }

  processOffer (endpoint, sdpOffer, cb) {
    endpoint.processOffer(sdpOffer, (error, sdpAnswer) => {
      if (error) {
        return error && error(error);
      }
      cb && cb(sdpAnswer);
    });

    endpoint.gatherCandidates((error) => {
      if (error) {
        return error && error(error);
      }
    });
  }

  stop () {

  }
}
